package com.project.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import org.springframework.web.bind.annotation.RestController;
import com.project.service.IUserService;
import com.project.util.WebSocketUtils;

@RestController
@Component
@ServerEndpoint("/tongzhi/{id}")
public class SocketlController {
	@Autowired
	private IUserService userService; 
	private WebSocketUtils util = new WebSocketUtils();
    
	@OnOpen
	public void openSession(@PathParam("id") Integer id, Session session) {		
		util.ONLINE_USER_SESSIONS.put(id, session);
		String message = "欢迎用户[" +id+ "] 来到聊天室！";
		System.out.println(message);
	}
	@OnMessage
	public void onMessage(@PathParam("id") Integer id , String message,HttpServletRequest req) {
		
		//发送的消息是%号来组合的 前面是发送给服务器的消息 后面是给接收方的id
		System.out.println("发送消息：" + message);
		//拆分字符串
		String[] s=message.split("%");
		String messages=s[0]+"%"+id;	
		int otherId=Integer.parseInt(s[1]);
		
		Session session=util.ONLINE_USER_SESSIONS.get(otherId);	
		util.sendMessage(session, messages);
	}
	
	@OnClose
	public void onClose(@PathParam("id") Integer id, Session session) { 
		// 当前的Session 移除
		 util.ONLINE_USER_SESSIONS.remove(id); 
		// 并且通知其他⼈当前⽤户已经离开聊天室了

		//util.sendMessageAll("用户[" + id + "] 已经离开聊天室了！"); 


		try {
			session.close();
		} catch (IOException e) {
			System.out.println("退出异常");
		}
	}
	@OnError
	 public void onError(Session session, Throwable throwable) {
	 try {
	 session.close();
	 } catch (IOException e) {
	 System.out.println("关闭异常");
	 }
}
	
}